package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.Util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取当前登录用户名（从JWT Token中获取）
     */
    private String getCurrentUsername(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token != null && jwtUtil.validateToken(token)) {
            return jwtUtil.getUsernameFromToken(token);
        }
        return null;
    }

    @PostMapping("/selectAllUser")
    public Result selectAllUser() {
        try {
            return Result.success(userService.findAllUser());
        } catch (Exception e) {
            return Result.error("查询用户列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/findUserByUsername")
    public Result findUserByUsername(String username) {
        try {
            User user = userService.findUserByUsername(username);
            if (user != null) {
                user.setPassword(null); // 不返回密码
                return Result.success(user);
            }
            return Result.notFound("用户名不存在");
        } catch (Exception e) {
            return Result.error("查询用户失败: " + e.getMessage());
        }
    }

    // 注册
    @PostMapping("/registerUser")
    public Result registerUser(@RequestBody User user) {
        try {
            int result = userService.registerUser(user);
            if (result > 0) {
                return Result.success("注册成功");
            } else {
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    // 通过邮箱号查询邮箱是否存在
    @GetMapping("/findUserByEmail")
    public Result findUserByEmail(String email) {
        try {
            User user = userService.findUserByEmail(email);
            if (user != null) {
                user.setPassword(null); // 不返回密码
                return Result.success(user);
            }
            return Result.notFound("邮箱不存在");
        } catch (Exception e) {
            return Result.error("查询邮箱失败: " + e.getMessage());
        }
    }

    @GetMapping("/sendEmailCode")
    public Result sendEmailCode(String email) {
        try {
            User user = userService.findUserByEmail(email);
            if (user != null) {
                userService.sendEmailCode(email);
                return Result.success("验证码发送成功");
            }
            return Result.notFound("邮箱号不存在");
        } catch (Exception e) {
            return Result.error("发送验证码失败: " + e.getMessage());
        }
    }

    @PutMapping("/updatePasswordByEmail")
    public Result updatePasswordByEmail(String email, String password, String code) {
        try {
            Boolean checkCode = userService.checkCode(email, code);
            if (checkCode) {
                int result = userService.updatePasswordByEmail(email, password);
                if (result > 0) {
                    return Result.success("密码修改成功");
                }
                return Result.error("密码修改失败");
            } else {
                return Result.error("验证码错误");
            }
        } catch (Exception e) {
            return Result.error("修改密码失败: " + e.getMessage());
        }
    }

    // 获取当前用户信息
    @GetMapping("/profile")
    public Result getCurrentUserProfile(HttpServletRequest request) {
        try {
            String username = getCurrentUsername(request);
            if (username == null) {
                return Result.error("用户未登录");
            }
            User user = userService.findUserByUsername(username);
            if (user != null) {
                // 不返回敏感信息
                user.setPassword(null);
                return Result.success(user);
            }
            return Result.notFound("用户不存在");
        } catch (Exception e) {
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    // 更新当前用户信息
    @PutMapping("/profile")
    public Result updateCurrentUserProfile(@RequestBody User user, HttpServletRequest request) {
        try {
            // 设置当前用户名，防止修改其他用户信息
            String currentUsername = getCurrentUsername(request);
            if (currentUsername == null) {
                return Result.error("用户未登录");
            }
            user.setUsername(currentUsername);

            int result = userService.updateUserInfo(user);
            if (result > 0) {
                return Result.success("个人信息更新成功");
            } else {
                return Result.error("个人信息更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新个人信息失败: " + e.getMessage());
        }
    }

    // 修改当前用户密码
    @PutMapping("/password")
    public Result changeCurrentUserPassword(@RequestBody Map<String, String> params, HttpServletRequest request) {
        try {
            String username = getCurrentUsername(request);
            if (username == null) {
                return Result.error("用户未登录");
            }
            String oldPassword = params.get("oldPassword");
            String newPassword = params.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return Result.error("参数不完整");
            }

            // 验证旧密码
            User user = userService.login(username, oldPassword);
            if (user == null) {
                return Result.error("原密码错误");
            }

            // 更新密码
            int result = userService.updatePassword(username, newPassword);
            if (result > 0) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            return Result.error("修改密码失败: " + e.getMessage());
        }
    }
}